package cn.jy.careuplusdoctor.main;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import cn.jy.careuplusdoctor.R;
import cn.jy.careuplusdoctor.base.BaseActivity;
import cn.jy.careuplusdoctor.http.HttpHelper;
import cn.jy.careuplusdoctor.http.HttpHelper.onHttpListener;
import cn.jy.careuplusdoctor.http.HttpUrls;
import cn.jy.careuplusdoctor.injector.IdInject;
import cn.jy.careuplusdoctor.response.DoctorIdResponse;
import cn.jy.careuplusdoctor.response.LoginResponse;
import cn.jy.careuplusdoctor.response.SendMassageResponse;
import cn.jy.careuplusdoctor.utils.Code;
import cn.jy.careuplusdoctor.utils.DesTool4Android;
import cn.jy.careuplusdoctor.utils.StringUtil;
import cn.jy.careuplusdoctor.widgets.CareuTitleBar.TitleBarLeftAction;
import cn.jy.careuplusdoctor.widgets.CareuTitleBar.TitleBarRightAction;

/**
 * 忘记密码
 */
public class ForgetPasswordActivity extends BaseActivity implements TitleBarLeftAction, TitleBarRightAction {
	@IdInject(id = R.id.txt_gain)
	private TextView		txt_gain;
	@IdInject(id = R.id.edt_phone)
	private EditText		edt_phone;
	@IdInject(id = R.id.edt_auth_code)
	private EditText		edt_auth_code;
	@IdInject(id = R.id.edt_new_password)
	private EditText		edt_new_password;
	@IdInject(id = R.id.edt_affirm_password)
	private EditText		edt_affirm_password;
	// @IdInject(id = R.id.btn_affirm)
	// private Button btn_affirm;
	private HandlerThread	thread;
	private Handler			handler, btnHandler;
	private int				btnTime	= 0;
	private String			checknum;
	private String			doctorId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_forget_password);
		initTitleBar();
		onInJectView();
		edt_auth_code.addTextChangedListener(new CodeEditChanged());
		Code.getInstance().createBitmap();
	}

	@Override
	protected void settingTitleBar() {
		super.settingTitleBar();
		getTitleBar().setLeftText("取消");
		getTitleBar().setTitle("忘记密码");
		getTitleBar().setLeftAction(this);
		getTitleBar().setRightAction(this);
		getTitleBar().getRighTextView().setVisibility(View.GONE);
		getTitleBar().getLeftImageView().setVisibility(View.GONE);
		getTitleBar().getRightImageView().setVisibility(View.GONE);
	}

	@Override
	public void onRightPress(View view) {
	}

	@Override
	public void onLeftPress(View view) {
		defaultFinish();
	}

	@Override
	protected void onAfterInJector() {
		super.onAfterInJector();
		OnClickListener onClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
					case R.id.txt_gain:
//						edt_auth_code.setEnabled(true);
						checkPhone();
						break;
					case R.id.btn_affirm:
						if (!StringUtil.isNotEmpty(edt_phone.getText().toString())) {
							return;
						} else if (!StringUtil.isNotEmpty(edt_auth_code.getText().toString())) {
							shortToast("验证码不能为空");
							return;
						}else if (!edt_auth_code.getText().toString().equals(checknum)) {
							shortToast("请输入正确验证码");
							return;
						}else if (!StringUtil.isNotEmpty(edt_new_password.getText().toString())) {
							shortToast("密码不能为空");
							return;
						} else if (6 > edt_new_password.getText().toString().length()
								|| edt_new_password.getText().toString().length() > 20) {
							shortToast("新密码长度不能少于6位");
							return;
						} else if (!edt_new_password.getText().toString()
								.equals(edt_affirm_password.getText().toString())) {
							shortToast("密码与确认密码不一致");
							return;
						} else {
							recoverPassword();
						}
						break;
				}
			}
		};
		findViewById(R.id.txt_gain).setOnClickListener(onClickListener);
		findViewById(R.id.btn_affirm).setOnClickListener(onClickListener);
	}

	/**
	 * 医生手机号码检验功能
	 */
	public void checkPhone() {
		if (!StringUtil.isNotEmpty(edt_phone.getText().toString())) {
			shortToast("请输入手机号");
			return;
		} else if (11 > edt_phone.getText().toString().length()) {
			shortToast("手机不能小于11位");
			return;
		}
		if (StringUtil.isMobile(edt_phone.getText().toString()) == false) {
			shortToast("手机号不合法");
			return;
		}
		String phone = edt_phone.getText().toString();
		HttpHelper.getInstance().checkPhone(phone, new onHttpListener<DoctorIdResponse>() {
			@Override
			public void onResponse(DoctorIdResponse data, int code) {
				hidenLoading();
				if (data != null && code == HttpUrls.REQUEST_SUCCESS) {
					if (TextUtils.equals("1", data.getResType())) {
						// 获取用户ID
						doctorId = data.getDoctorId();
						sendSMS();
					}
					else if (TextUtils.equals("-1", data.getResType())) {
						shortToast("网络故障，获取失败");
					}
					else if (TextUtils.equals("2", data.getResType())) {
						shortToast("手机号码未注册");
					}
				} else {
					shortToast("网络故障，获取失败");
				}
			}
		});
	}

	/**
	 * 验证成功跳转到获取验证码
	 * 
	 * @param doctorId
	 */
	public void sendSMS() {
		// 启动倒计时
		runTimer();
		String tokenStr = "";
		// 验证码
		checknum = Code.getInstance().getCode().toString();
		try {
			tokenStr = DesTool4Android.getToken(edt_phone.getText().toString(), checknum);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String content = "尊敬的用户，您正在修改慢糖生活APP会员密码,验证码：" + checknum + "【广州嘉祐】";
		try {
			HttpHelper.getInstance().sendMessage(URLEncoder.encode(tokenStr,"UTF-8"), content, new onHttpListener<SendMassageResponse>() {
				@Override
				public void onResponse(SendMassageResponse data, int code) {
					if (data != null && code == HttpUrls.REQUEST_SUCCESS) {
						if (TextUtils.equals("1", data.getResType())) {
						} else {
							shortToast(data.getMsg());
						}
					} else {
						shortToast("网络故障，获取失败");
					}
				}
			});
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 重新设置密码功能
	 */
	public void recoverPassword() {
		String new_password = edt_new_password.getText().toString().trim();
		String tokenStr = "";
		try {
			tokenStr = DesTool4Android.getToken(doctorId, new_password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		showLoading("正在设置...");
		try {
			HttpHelper.getInstance().recoverPassword(URLEncoder.encode(tokenStr,"UTF-8"), new onHttpListener<LoginResponse>() {
				@Override
				public void onResponse(LoginResponse data, int code) {
					hidenLoading();
					if (data != null && code == HttpUrls.REQUEST_SUCCESS) {
						if (TextUtils.equals("1", data.getResType())) {
							shortToast(data.getMsg());
							defaultFinish();
						} else {
							shortToast(data.getMsg());
						}
					} else {
						shortToast("网络故障，密码修改失败");
					}
				}
			});
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 60秒倒计时
	 */
	Thread	_t;

	public void runTimer() {
		if (txt_gain != null) {
			btnTime = 60;
			txt_gain.setClickable(false);
			txt_gain.setEnabled(false);
			thread = new HandlerThread("co	unt", btnTime);
			thread.start();
			handler = new Handler(thread.getLooper());
			btnHandler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					if (msg.arg1 <= 0) {
						txt_gain.setClickable(true);
						txt_gain.setEnabled(true);
						txt_gain.setTextColor(Color.parseColor("#1E87F0"));
						txt_gain.setText("获取验证码");
					} else {
						txt_gain.setTextColor(Color.parseColor("#A1A1A1"));
						txt_gain.setText(String.format("重新获取（%d）", msg.arg1));
					}
				}
			};
			_t = new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						while (btnTime >= 0) {
							Message message = new Message();
							btnTime--;
							message.arg1 = btnTime;
							btnHandler.sendMessage(message);
							Thread.sleep(1000);
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
			handler.post(_t);
		}
	}

	/**
	 * 验证码监听器
	 * 
	 */
	class CodeEditChanged implements TextWatcher {
		@Override
		public void afterTextChanged(Editable editable) {
		}

		@Override
		public void beforeTextChanged(CharSequence charsequence, int i, int j, int k) {
		}

		@Override
		public void onTextChanged(CharSequence charsequence, int i, int j, int k) {
			/**
			 * 验证码为6位数
			 */
			if (charsequence.length() == 6) {
				if (edt_auth_code.getText().toString().equals(checknum)) {
					edt_phone.setEnabled(false);
//					 edt_auth_code.setEnabled(false);
					shortToast("验证成功");
				}
			}
		}
	}
}
